<template>
  <div class="app-container">
    <div v-show="!modifyInfo.visible && !detailInfo.visible && !detailListInfo.visible">
      <!-- 条件栏 -->
      <div class="filter-wrapper">
        <NewPageFilter
          ref="pageFilter"
          v-model:query="filterInfo.query.queryMap"
          :query-more-json="true"
          :filter-list="filterInfo.searchList"
          :filter-btn="filterInfo.searchBtn"
          :clear-type="clearType"
          :slip-select-request="slipSelectRequest"
        >
        </NewPageFilter>
        <el-button @click="detailListInfo.visible = true">明细页</el-button>
      </div>
      <div class="filter-wrapper">
        <NewPageFilter :filter-btn="filterInfo.btList">
          <!-- <template v-slot:filter-print>
            <el-button  @click="print()">打印</el-button>
          </template> -->
          <template v-slot:filter-excel>
            <el-button  @click="exportExcel()"
              >导出excel</el-button
            >
          </template>
          <template v-slot:filter-del>
            <el-button :disabled="!canDelete" @click="del()">删除</el-button>
          </template>
        </NewPageFilter>
        <div class="display-flex">
          <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
        </div>
      </div>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :tab-index="false"
        :check-box="true"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowOtherClassName"
        @pageInfo="pageInfo"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-orderNo="scope">
          <p class="slip-edit" @click="showProductDetail(scope.row)">
            {{ scope.row.orderNo || '-' }}
          </p>
        </template>
      </table-container>
    </div>
    <!-- 新增或修改 -->
    <deviceMaintenancePlan-modify
      v-if="modifyInfo.visible"
      :id="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      @returnModify="returnModify"
    />

    <!-- 详情页 -->
    <deviceMaintenancePlan-detail
      v-if="detailInfo.visible"
      :id="detailInfo.id"
      v-model:visible="detailInfo.visible"
      :title="detailInfo.title"
      @returnBack="getList"
    />

    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      @callback="setPreferenceCallback"
    />
    <advanced-search
      v-if="advancedSearchInfo.visible"
      v-model:visible="advancedSearchInfo.visible"
      :field-list="tableInfo.fieldList"
      v-model:form-data="advancedSearchInfo.data"
      @callback="advancedSearchCallback"
    />
    <chose-printer
      :visible="printerInfo.visible"
      @callBack="handlePrinterCallBack"
    />
    <DetailList
      v-if="detailListInfo.visible"
      v-model:visible="detailListInfo.visible"
      @callback="getList"
    ></DetailList>
    <page-dialog
      v-show="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </page-dialog>
  </div>
</template>

<script setup name="patrolRecordRegistration">
import {
  getPatrolRecoredCustomizeListPage,
  deleteRecored,
  excelRecoredOrderList,
  printRecoredOrderList,
} from '@/api/patrol.js'
import PageDialog from '@/components/PageDialog/index'
import chosePrinter from '@/components/ChosePrinter'
import DeviceMaintenancePlanModify from './modify.vue'
import DeviceMaintenancePlanDetail from './detail.vue'
import { fatchTemplateByCode } from '@/api/base'
import { getCustomizeSetting, updateUserCustomize } from '@/api/customize'
import { getDepotAll } from '@/api/core'
import DetailList from './detailList'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const TableContainer = defineAsyncComponent(() =>
  import('@/components/TableContainer/index')
)

const SetPreference = defineAsyncComponent(() =>
  import('@/components/SetPreference/index')
)
const AdvancedSearch = defineAsyncComponent(() =>
  import('@/components/AdvancedSearch/index')
)
const props = defineProps(['query'])

const clearType = ref(true)
const slipSelectRequest = ref(true)
const printerInfo = reactive({
  visible: false,
  data: {},
})
const dialogInfo = reactive({
  visible: false,
  title: '提示',
  btLoading: false,
  type: '',
  msg: '',
  width: '400px',
  flag: true,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '打印',
      type: 'primary',
      event: checkConfirm,
      show: true,
    },
  ],
})

const filterInfo = reactive({
  query: {
    sortString: '',
    customizeUserVO: {},
    queryMap: {},
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: 'button', label: '搜索', event: search },
    // { type: 'button', label: '高级查询', event: advancedSearchShow },
    { type: 'button', label: '重置', event: clearSearch },
  ],
  btList: [
    {
      type: 'button',
      label: '新增',
      event: create,
      show: proxy.$permission('patrolRecordRegistration:add'),
    },
    {
      type: 'slot',
      value: 'del',
      show: proxy.$permission('patrolRecordRegistration:del'),
    },
    {
      type: 'slot',
      value: 'excel',
      show: proxy.$permission('patrolRecordRegistration:excel'),
    },
    {
      type: 'slot',
      value: 'print',
      show: proxy.$permission('patrolRecordRegistration:print'),
    },
  ],
})

const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
      {
        label: '修改',
        event: update,
        show: proxy.$permission('patrolRecordRegistration:update'),
      },
      {
        label: '删除',
        event: del,
        popconfirmText: '删除后将改变数据,是否继续？',
        show: proxy.$permission('patrolRecordRegistration:del'),
      },
    ],
  },
})

const canDelete = computed(() => {
  return tableInfo.selections.length
})
const detailListInfo = reactive({
  visible: false,
})
//明细相关
const detailInfo = reactive({
  visible: false,
  title: '巡检记录登记详情',
  id: '',
})
//新增或更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
})

const preferenceInfo = reactive({
  visible: false,
})

const advancedSearchInfo = reactive({
  visible: false,
  data: {},
})

let page = reactive({
  page: true,
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
})

let obj = {
  
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function update(row) {
  sessionStorage.setItem('storeRowId', row.id)
  modifyInfo.id = row.id
  modifyInfo.visible = true
  modifyInfo.title = '修改巡检记录登记'
}
// 创建
function create() {
  modifyInfo.visible = true
  modifyInfo.title = '新增巡检记录登记'
  modifyInfo.id = null
}
function showProductDetail(row) {
  sessionStorage.setItem('storeRowId', row.id)
  detailInfo.visible = true
  detailInfo.title = '巡检记录登记详情'
  detailInfo.id = row.id
}
function tableRowOtherClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function returnModify() {
  if (modifyInfo.id) {
    getList()
  } else {
    search()
  }
}
function pageInfo(obj) {
  page = obj
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value)
    }
  })
}
function advancedSearchShow() {
  advancedSearchInfo.visible = true
}
async function advancedSearchCallback(obj) {
  filterInfo.query.queryMap = {}
  let arr = [
    {
      asTbName: 'repair_order',
      columnName: 'repair_dept_id',
      queryType: 'IN',
      queryCategory: 'AND',
      value: 'deptAuth',
    },
  ]
  filterInfo.query.queryDtoList = [...obj.queryDtoList, ...arr]
  advancedSearchInfo.data = obj.data

    await getList()
  
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  clearType.value = !clearType.value
}
async function getList() {
  tableInfo.refresh = Math.random()
}
function search() {
  advancedSearchInfo.data = {}
  filterInfo.query.queryDtoList = []

    tableInfo.initCurpage = Math.random()
    tableInfo.refresh = Math.random()
  
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function clearSearch() {
  clearType.value = !clearType.value
  filterInfo.query.queryMap = proxy.$fn.deepClone(filterInfo.copyQueryMap)
  search()
}
function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      'patrolRecoredList-com.slip.spd.entity.vo.patrol.PatrolRecoredVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail,
        true
      )

      tableInfo.fieldList = tableFieldInfo.fieldList
      filterInfo.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.query.queryMap,
      }
      filterInfo.copyQueryMap = proxy.$fn.deepClone(filterInfo.query.queryMap)
      filterInfo.searchList = searchInfo.searchList
      filterInfo.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = _slipSelectRequest
      tableInfo.api = getPatrolRecoredCustomizeListPage
      getList()
    }
  })
}

function handlePrinterCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.data, printer)
  }
  printerInfo.visible = false
}

function checkConfirm() {
  if (dialogInfo.type === 'excel') {
    exportExcelList()
  } else if (dialogInfo.type === 'print') {
    printList()
  }
  dialogInfo.visible = false
  dialogInfo.msg = ''
}
function handleClose() {
  dialogInfo.visible = false
}
function exportExcel() {
  dialogInfo.visible = true
  dialogInfo.type = 'excel'
  dialogInfo.msg = '请选择数据导出范围'
  dialogInfo.btList[1].label = '导出'
  dialogInfo.flag = true
}
function exportExcelList() {
  let params = {
    ...filterInfo.query,
    ...page,
    page: dialogInfo.flag,
  }
  excelRecoredOrderList(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

async function print() {
  dialogInfo.visible = true
  dialogInfo.type = 'print'
  dialogInfo.msg = '请选择当数据打印范围'
  dialogInfo.btList[1].label = '打印'
  dialogInfo.flag = true
}

function printList() {
  fatchTemplateByCode({
    resourceCode: 'deviceMaintenancePlan:print',
    isDefault: 1,
  }).then((res) => {
    if (res && res.success) {
      let temp = proxy.$fn.getPrintTemp(res.data[0])
      getPrintData(temp, dialogInfo.flag)
    }
  })
}
function getPrintData(temp, flag) {
  let query = {
    customizeDto: filterInfo.query,
  }
  let params = {
    ...query,
    ...page,
    page: flag,
  }
  printRecoredOrderList(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
//删除
function del(row = undefined) {
  const ids = _getIds(row)
  if (row && row.id) {
    deleteRecored(ids).then((resp) => {
      if (resp && resp.success) {
        getList()
      }
    })
  } else {
    proxy
      .$confirm('删除后将改变数据,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      .then(() => {
        deleteRecored(ids).then((resp) => {
          if (resp && resp.success) {
            getList()
          }
        })
      })
  }
}
function _getIds(row) {
  let ids = []
  if (row && row.id) {
    ids = [row.id]
  } else {
    if (tableInfo.selections.length > 0) {
      ids = tableInfo.selections.map((row) => row.id)
    }
  }
  return ids
}
</script>

<style scoped></style>
